
function showLoading() {
  wx.showLoading({
    title: '加载中',
    mask: true
  });
}

function hideLoading() {
  wx.hideLoading();
}

function showErrorToast(message) {
  wx.showToast({
    title: message,
    icon: 'none',
    duration: 3000
  });
}
/**
 * 封装请求
 */
function fetch(options) {
  if (options.loading) {
    showLoading();
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: options.url,
      data: options.data,
      header: {
        "Content-Type": options.contentType
      },
      method: options.method,
      success: function (res) {
        res = res.data;
        if (options.loading) {
          hideLoading();
        }
        if (res.code !== 200) {
          showErrorToast("请求失败");
          return reject(new Error("Request failed"));
        }
        resolve(res); //把请求到的数据发到引用请求的地方
      },
      fail: function (err) {
        if (options.loading) {
          wx.hideLoading()
        }
        showErrorToast("网络连接超时");
        reject(err);
      }
    })
  })
}
/**
 * POST 请求
 */
const post = function post(url, params, loading = true, contentType = "application/json") {
  let option = {
    url: url,
    data: params,
    method: 'POST',
    loading,
    contentType
  }
  return fetch(option);
}

/**
 * GET请求
 */
const get = function get(url, params, loading = true) {
  let option = {
    url: url,
    data: params,
    method: 'GET',
    loading
  }
  return fetch(option);
}
module.exports = {
  post,
  get,
}
